package reduce.fz.com.reduce.fragment.base;


import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.alibaba.fastjson.TypeReference;

import java.util.ArrayList;
import java.util.List;

import reduce.fz.com.reduce.R;
import reduce.fz.com.reduce.abstracts.AbRecycleScroollListener;
import reduce.fz.com.reduce.adapter.BaseListAdapter;
import reduce.fz.com.reduce.adapter.BaseRecycleViewHolder;
import reduce.fz.com.reduce.bean.page.Pagination;
import reduce.fz.com.reduce.bean.result.Result;
import reduce.fz.com.reduce.custom.LoadingDialog;
import reduce.fz.com.reduce.fragment.BaseViewPagerFragment;

public abstract class BaseListFragment<VH extends BaseRecycleViewHolder, VC> extends BaseViewPagerFragment {
    //Adapter
    protected BaseListAdapter<VH, VC> baseListAdapter;

    private Boolean noMore = false;
    //上下文
    protected Context context;
    //分页
    private Pagination pagination = new Pagination();
    //刷新
    private SwipeRefreshLayout swipeRefreshLayout;
    //滑动view
    protected RecyclerView recyclerView;

    protected LayoutInflater layoutInflater;

    private LinearLayoutManager mLayoutManager;
    private Boolean isRefresh = false;
    //loading加载框
    protected LoadingDialog loadingDialog = null;
    //首次进入是否已经做loadingDiialog加载
    private Boolean supportLoadingDialog = true;

    private Boolean isRequesting = false;
    private LinearLayout mNoInfo;

    private View view = null;


    public int getIndex(VC o) {
        return baseListAdapter.datas.indexOf(o);
    }

    public int getHeaderIndex(VC o)
    {
        return baseListAdapter.headerDatas.indexOf(o);
    }

    public void remove(int positon) {
        baseListAdapter.datas.remove(positon);
        baseListAdapter.notifyContentItemRemoved(positon);
    }

    public void remove(VC o)
    {
        int position=getIndex(o);
        if(position>=0)
        {
            remove(position);
        }

    }
    public void addHeader(VC o)
    {
        mNoInfo.setVisibility(View.GONE);
        baseListAdapter.headerDatas.add(o);
        baseListAdapter.notifyHeaderItemInserted(baseListAdapter.headerDatas.size() - 1);
    }


    public void addFrist(VC o) {
        mNoInfo.setVisibility(View.GONE);
        baseListAdapter.datas.add(0, o);
        baseListAdapter.notifyContentItemInserted(0);
        scrollTo(0);
    }
    public void dataChange(VC o){
        int position=getIndex(o);
        if(position>=0) {
            baseListAdapter.datas.set(position, o);
            baseListAdapter.notifyContentItemChanged(position);
        }
    }


    public void addLast(VC o) {
        mNoInfo.setVisibility(View.GONE);
        baseListAdapter.datas.add(o);
        baseListAdapter.notifyContentItemInserted(baseListAdapter.datas.size() - 1);

    }


    //双排流使用
    public static final class DefaultSpanSizeLookup extends GridLayoutManager.SpanSizeLookup {
        private BaseListAdapter adapter;
        private int spansize;

        public DefaultSpanSizeLookup(BaseListAdapter baseListAdapter,int spansize) {
            adapter = baseListAdapter;
            this.spansize=spansize;
        }

        @Override
        public int getSpanSize(int position) {
            int hc = adapter.getHeaderItemCount();
            int cc = adapter.getContentItemCount();
            if (position < hc) {
                return spansize;
            } else if (position < cc + hc) {
                return 1;
            } else {
                return spansize;
            }
        }


        @Override
        public int getSpanIndex(int position, int spanCount) {
            return adapter.getSpanIndex(position, spanCount);
        }
    }

    /**
     * 设置是否首次弹出加载框，默认是
     *
     * @param support
     */
    public void setSupportLoadingDialog(Boolean support) {
        this.supportLoadingDialog = support;
    }

    //请求URL
    public void requestData(String url) {
        if (noMore) {
            baseListAdapter.setFooterNoMore();
            return;
        }
        beforeRequest();
        request(url);
    }

    public void endRequest() {
        // baseListAdapter.setFooterNormal();
    }

    public void beforeRequest() {
        baseListAdapter.setFooterLoading();
    }

    public void request(String url) {

    }

    public void refresh() {
        firstPage();
    }

    public void setStartNum(Long startNum) {
        pagination.setStartNum(startNum);
    }

    public List<VC> filterData(List<VC> data) {
        List<VC> temp = new ArrayList<VC>();
        if (data == null || data.size() == 0) return null;
        for (int i = 0; i < data.size(); i++) {
            if (!data.contains(data))
                temp.add(data.get(i));
        }
        return temp;
    }


    public void addResult(Result<List<VC>> data) {
        mNoInfo.setVisibility(View.GONE);
        isRequesting = false;
        baseListAdapter.setFooterNormal();
        if(data==null) return;
        if (!data.isSuccess()) return;
        List<VC> values = filterData(data.getData());
        if (values != null && !values.isEmpty()) {
            if(isRefresh&&values.size()<pagination.getPageSize())
            {
                noMore = true;
                baseListAdapter.setFooterNoMore();
            }

            if (isRefresh) {
                baseListAdapter.initDatas(values);
            } else {
                baseListAdapter.addDatas(values);
            }
        } else {
            if(isRefresh)mNoInfo.setVisibility(View.VISIBLE);
            noMore = true;
            baseListAdapter.setFooterNoMore();
        }
        if (isRefresh) {
            recyclerView.scrollToPosition(0);
        }
        // if (loadingDialog != null && loadingDialog.isShowing())
        loadingDialog.dismiss();

    }

    public void setBackgroundColor(int resid) {
        view.findViewById(R.id.ll_base_list).setBackgroundResource(resid);

    }

    public BaseListFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        layoutInflater = inflater;
        view = layoutInflater.inflate(R.layout.fragment_baselist, null);
        loadingDialog = new LoadingDialog(this.getActivity());
        if (supportLoadingDialog) {
            // loadingDialog.show();
        }



        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        this.recyclerView = initRecycleView(view);
        this.swipeRefreshLayout = initSwipeRefresh(view);
        this.context = this.getActivity().getBaseContext();
        //loadingDialog = new LoadingDialog(getActivity());
        pagination.pageType = getPageType();
        mNoInfo= (LinearLayout) view.findViewById(R.id.ll_no_info);
        initListAdapter();
        initRecycleView();
        this.recyclerView.setAdapter(this.baseListAdapter);
        firstPage();

    }

    protected void scrollTo(int position) {
        recyclerView.scrollToPosition(position);
    }

    private RecyclerView initRecycleView(View view) {
        return (RecyclerView) view.findViewById(R.id.base_list_view);
    }

    public int getSize() {
        return baseListAdapter.datas.size();
    }

    private SwipeRefreshLayout initSwipeRefresh(View view) {
        return (SwipeRefreshLayout) view.findViewById(R.id.base_swipe_refresh);
    }



    /**
     * 获取LayoutManager，兼容GridLayoutManager
     *
     * @return
     */
    public abstract LinearLayoutManager getLayoutManager();

    /**
     * 创建item card
     *
     * @param parent
     * @return
     */
    protected abstract VH createItemViewHolder(ViewGroup parent);

    /**
     * 创建foot
     *
     * @param view
     * @return
     */
    protected abstract VH createfootViewHolder(View view);


    protected VH createHeaderViewHolder(ViewGroup parent){
        return null;

    }
    /**
     * 在请求之前获取url,如果为statNum类型的分页方式，需要讲startNUm重设到pagination中
     *
     * @param datas
     * @param pagination
     * @return
     */
    protected abstract String setUrlBeforeRequest(List<VC> datas, Pagination pagination);

    //获取分页类型，默认pageNo
    protected abstract int getPageType();

    public void initListAdapter() {
        this.baseListAdapter = new BaseListAdapter<VH, VC>(context) {
            @Override
            public VH createFooterStatusViewHolder(View footerView) {
                return createfootViewHolder(footerView);
            }

            @Override
            public VH createViewHolder(ViewGroup parent) {
                return createItemViewHolder(parent);
            }

            @Override
            public VH createHeaderHolder(ViewGroup parent) {
                return createHeaderViewHolder(parent);
            }
        };
    }

    public String combUrl(Pagination pagination) {
        String url = setUrlBeforeRequest(baseListAdapter.datas, pagination);
        return url;
    }

    //翻下一页
    public void nextPage() {
        if (noMore) return;
        if (isRequesting) return;
        isRefresh = false;
        pagination.nextPage();
        String url = combUrl(pagination);
        requestData(url);

    }

    public void setNoMore() {
        noMore = true;
    }

    //翻第一页
    public void firstPage() {
        if (isRequesting) return;
        isRefresh = true;
        noMore = false;
        pagination.reset();
        baseListAdapter.clearDatas();
        String url = combUrl(pagination);
        isRequesting = true;
        requestData(url);
    }

    public int getSpanSize() {
        return 2;
    }
    public void initRecycleView() {
        if (getLayoutManager() != null) {
            mLayoutManager = getLayoutManager();
            if (mLayoutManager instanceof GridLayoutManager) {
                DefaultSpanSizeLookup defaultSpanSizeLookup = new DefaultSpanSizeLookup(baseListAdapter,getSpanSize());
                ((GridLayoutManager) mLayoutManager).setSpanSizeLookup(defaultSpanSizeLookup);
            }
        } else {
            mLayoutManager = new LinearLayoutManager(this.getActivity().getBaseContext());
        }
        // 设置ItemAnimator
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        // 设置固定大小
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setOnScrollListener(new AbRecycleScroollListener(mLayoutManager) {
            @Override
            public void onLoadMore() {
                nextPage();
            }
        });
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                firstPage();
                swipeRefreshLayout.setRefreshing(false);
            }
        });

    }
}
